<?php
namespace Api\Service;
use Common\Util\Convert;
use Think\Log;
/**
 * 接口返回值 服务Service
 */
class UserService {
    
    public function validateParam($param){
        switch ($param['method']) {
            case 'user_info':
                if(empty($param['code'])) {
                    E('code不能为空！');
                }
                if(empty($param['iv'])) {
                    E('iv不能为空！');
                }
                if(empty($param['encryptedData'])) {
                    E('encryptedData不能为空！');
                }
                break;
            default: 
                return '';
        }
    }
    
    /**
     * {
    "openId": "OPENID",
    "nickName": "NICKNAME",
    "gender": GENDER,
    "city": "CITY",
    "province": "PROVINCE",
    "country": "COUNTRY",
    "avatarUrl": "AVATARURL",
    "unionId": "UNIONID",
    "watermark":
    {
        "appid":"APPID",
    "timestamp":TIMESTAMP
    }
}
     * @param unknown $param
     */
    public function addUser($param){
        Log::writeInfo('start to save in UserService, param:' .json_encode($param),'user');
        $user = json_decode($param, true);
        $where = array('union_id'=>$user['unionId']);
        $userInDb = M('user')->where($where)->find();
        
        Convert::camel2Underscore($user);
        $user['nickname'] = $user['nick_name'];
        if(!empty($userInDb)) {
            $res = M('user')->where($where)->save($user);
            $user['id'] = $userInDb['id'];
            return $user;
        }

        $id = M('user')->add($user);
        $user['id'] = $id;

        return $user;
    }

    /**
     * 获取用户个人信息
     * @param $creatorIdList
     * @return array
     */
    public function getMapByUids($uids){
        //查询用户信息
        $map = array('id' => array('in', $uids));
        $creatorList = M('User')->where($map)->field('id, nickname, avatar_url')->select();

        $creatorMap = array();
        foreach ($creatorList as $key => $val) {
            $creatorMap[$val['id']] = $val;
        }
        return $creatorMap;
    }

    /**
     * 获取用户unionId
     */
    public function getUnionId($uid)
    {
        $model = M('User');
        $res = $model->where(array( 'id' => $uid))->select();
        $unionId = $res[0]['union_id'];
        return $unionId;
    }

}
